const app = getApp();
// 
Page({
  data: {
    // intervalTime: 20000, // 刷新间隔时间
    intervalTime: 200000, // 刷新间隔时间
    polyline: [{
      points: [{
        longitude: 113.466697,
        latitude: 22.221247
      }, {
        longitude: 113.562183,
        latitude: 22.282487
      }],
      color: '#333333',
      width: 5,
      arrowLine: true,
    }],
  },
  onLoad: function() {
    let this_ = this;
    app.showLoading('加载中...', true)
    this.setData({
      selectCity: app.globalData.selectCity,
      Checkitem: app.globalData.BusCheckitem,
      // Checkitem: {
      //   BeginTime: "06:25",
      //   Description: "",
      //   Direction: 1,
      //   EndTime: "22:30",
      //   FromStation: "南屏科技园",
      //   Id: "8781b319-2513-4460-acfc-1bec6318c69a",
      //   Interval: "8.8",
      //   LineNumber: "15路",
      //   Name: "15路",
      //   Price: "1",
      //   StationCount: 28,
      //   ToStation: "香洲",
      // }
    })
    this.getLine();
    // that.setData({
    //   systemInfo: app.globalData.systemInfo,
    // })
    // that.getNearby();
    // that.getNearTrafficSt();
    // // that.getSave();
    // that.setData({
    //   weather: app.globalData.weather
    // })
  },
  onShow: function() {
    // let that = this;
    // if (that.data.Checkinterval) {
    //   console.log("来了Bus");
    //   let Checkinterval = setInterval(e => {
    //     that.checkNow()
    //   }, that.data.intervalTime);
    //   that.setData({
    //     Checkinterval,
    //   })
    //   that.checkNow();
    // }
  },
  onHide: function() {
    // let that = this;
    // console.log("去了Bus");
    // clearInterval(that.data.Checkinterval);
  },
  // 更换当前实时公交路线方向
  switchLine: function() {
    let this_ = this;
    if (this.data.selectCity == '珠海') {
      let time = Math.round(new Date().getTime() / 1000) + "000"
      let dataArr = {
        url: 'http://www.zhbuswx.com/Handlers/BusQuery.ashx?handlerName=GetLineListByLineName&key=' + this_.data.Checkitem.LineNumber + '&_=' + time,
        what: "Bus"
      }
      app.reGetFn(app.globalData.url, dataArr).then(e => {
        if (e.data == null || e.data == "") {
          this_.switchLine();
        } else if (e.data.data.length < 2) {
          console.log('只有一个方向')
        } else {
          let data = e.data.data;
          for (const i in data) {
            if (data[i].Id != this_.data.Checkitem.Id) {
              clearInterval(this_.data.Checkinterval);
              this_.setData({
                Checkitem: data[i],
              })
              this_.getLine();
              break;
            }
          }
        }
      })
    } else if (this.data.selectCity == '中山') {
      let lastone = this_.data.Checkitem.lineId[this_.data.Checkitem.lineId.length - 1] * 1,
        length = this_.data.Checkitem.lineId.length,
        Checkitem = this_.data.Checkitem,
        cut = this_.data.Checkitem.lineId.substring(0, length - 1);
      if (lastone == 0) cut += 1
      else if (lastone == 1) cut += 0
      Checkitem.lineId = cut;
      this_.setData({
        Checkitem
      })
      clearInterval(this_.data.Checkinterval);
      this_.getLine();
    }
  },
  // 获取路线车站列表
  getLine: function() {
    let that = this,
      time = new Date().getTime() / 1000,
      dataArr = [],
      url = '',
      hub = '';
    if (app.globalData.selectCity == '中山') {
      dataArr = {
        lineId: that.data.Checkitem.lineId,
        lineName: that.data.Checkitem.name,
        direction: that.data.Checkitem.direction,
        lineNo: that.data.Checkitem.lineNo,
        s: 'h5',
        v: '3.1.8',
        src: 'webapp_zhongshan',
        userId: 'browser_1546191266085',
        h5Id: 'browser_1546191266085',
        sign: '1',
        cityId: '021',
      };
      url = 'https://zhongshan.yg84.com/api/bus/line!lineDetail.action';
      hub = 'direct';
      app.reGetFn(url, dataArr, hub).then(e => {
        let ygkj = e.data.split('YGKJ')[1],
          arr = [];
        ygkj = JSON.parse(ygkj).jsonr.data
        let Checkinterval = setInterval(e => {
          that.checkNow()
        }, that.data.intervalTime);
        that.checkNow();
        that.setData({
          StationArr: ygkj,
        })
        wx.createSelectorQuery().select('.nowMsgBoxFather').boundingClientRect(function(rect) {
          that.setData({
            Checkinterval,
            nowMsgBoxFatherHeight: rect.height
          })
        }).exec();
        app.hideLoading();
      })
    } else if (app.globalData.selectCity == '珠海') {
      dataArr = {
        url: 'http://www.zhbuswx.com/Handlers/BusQuery.ashx?handlerName=GetStationList&lineId=' + that.data.Checkitem.Id + '&_=' + time,
        what: "Bus"
      };
      url = app.globalData.url;
      app.reGetFn(url, dataArr, hub).then(e => {
        if (e.data == null || e.data == "")
          that.getLine();
        else {
          let Checkinterval = setInterval(e => {
            that.checkNow()
          }, that.data.intervalTime);
          that.checkNow();
          e.data.data[e.data.data.length - 1].lastOne = true
          wx.createSelectorQuery().select('.nowMsgBoxFather').boundingClientRect(function(rect) {
            that.setData({
              StationArr: e.data.data,
              Checkinterval,
              nowMsgBoxFatherHeight: rect.height
            })
            that.makeMapLine();
          }).exec();
          app.hideLoading();
        }
      })
    }
  },
  // 设置map路线
  makeMapLine: function(e) {
    let this_ = this,
      stationArr = app.coolCopy(this.data.StationArr),
      lineArr = [];
    for (const i in stationArr) {
      let lat = stationArr[i].Lat * 1 - 0.003 * 1;
      let lng = stationArr[i].Lng * 1 + 0.005 * 1;
      lineArr[i] = {
        longitude: lng,
        latitude: lat
      };
    }
    console.log(lineArr)
    this.setData({
      polyline: [{
        points: lineArr,
        color: '#333333',
        width: 5,
        arrowLine: true,
      }]
    })
    console.log(this.data.polyline)


    113.566132, 22.278802
    113.56218, 22.282487

  },
  // 深复制
  coolCopy: function(a) {
    var c = {};
    c = JSON.parse(JSON.stringify(a));
    return c;
  },
  // 获取实时线路信息
  checkNow: function() {
    let that = this,
      time = new Date().getTime() / 1000,
      data = this.data;
    that.setData({
      refreshHidden: 'ok',
    })
    setTimeout(e => {
      that.setData({
        refreshHidden: '',
      })
    }, 2500)
    if (app.globalData.selectCity == '中山') {
      let dataArr = {
          lineId: that.data.Checkitem.lineId,
          lineName: that.data.Checkitem.name,
          direction: that.data.Checkitem.direction,
          lineNo: that.data.Checkitem.lineNo,
          s: 'h5',
          v: '3.1.8',
          src: 'webapp_zhongshan',
          userId: 'browser_1546191266085',
          h5Id: 'browser_1546191266085',
          sign: '1',
          cityId: '021',
        },
        url = 'https://zhongshan.yg84.com/api/bus/line!lineDetail.action',
        hub = 'direct';
      app.reGetFn(url, dataArr, hub).then(e => {
        let ygkj = e.data.split('YGKJ')[1],
          arr = [];
        ygkj = JSON.parse(ygkj).jsonr.data
        ygkj.stations[ygkj.stations.length - 1].lastOne = true
        let stationArr = app.coolCopy(ygkj.stations),
          buses = app.coolCopy(ygkj.buses);
        for (const k in buses)
          for (const i in stationArr) {
            if (buses[k].order == i * 1 + 1) {
              stationArr[i].haveBus = true;
              if (stationArr[i].busList == undefined) stationArr[i].busList = [];
              stationArr[i].busList.push(buses[k])
              continue;
            }
          }
        console.log('公交查询一次', stationArr);
        app.hideLoading();
        stationArr[0].fristOne = true
        that.setData({
          Checkmove: stationArr,
          nowCurrent: 1,
        })
      })
    } else if (app.globalData.selectCity == '珠海') {
      let dataArr = {
        url: decodeURIComponent('http://www.zhbuswx.com/Handlers/BusQuery.ashx?handlerName=GetBusListOnRoad&lineName=' + data.Checkitem.Name + '&fromStation=' + data.Checkitem.FromStation + '&_=' + time),
        what: "Bus"
      }
      app.reGetFn(app.globalData.url, dataArr).then(e => {
        if (e.data == null || e.data == "")
          that.checkNow();
        else {
          let edata = e.data.data,
            stationArr = app.coolCopy(that.data.StationArr);
          for (let i in edata)
            for (let k in stationArr) {
              if (edata[i].CurrentStation == stationArr[k].Name) {
                stationArr[k].haveBus = true;
                if (stationArr[k].busList == undefined) stationArr[k].busList = [];
                stationArr[k].busList.push(edata[i])
                continue;
              }
            }
          console.log('公交查询一次', stationArr);
          app.hideLoading();
          that.setData({
            Checkmove: stationArr,
            nowCurrent: 1,
          })
        }
      })
    }
  },
  // 取消收藏方法 
  NotkeepLine: function(e) {
    let that = this;
    let item = e.currentTarget.dataset.item;
    console.log("取消收藏")
    console.log(item)
    let save = wx.getStorageSync("save"); // 获取制定缓存 
    let newSave = [];
    for (let i in save) {
      if (save[i].item.Id == item.Id) {
        console.log("有一样的喔")
      } else {
        newSave[newSave.length] = save[i];
      }
    }
    console.log(save)
    console.log(newSave)
    that.setData({
      busArr: that.data.busArr,
      saveSt: newSave,
      saveStLenght: newSave.length,
    })
    wx.setStorageSync("save", newSave) // 设置制定缓存 
  },
  // 收藏方法 
  keepLine: function(e) {
    let that = this;
    let item = e.currentTarget.dataset.item;
    console.log("收藏")
    let save = wx.getStorageSync("save"); // 获取制定缓存 
    if (save == "") {
      save = [];
    }
    let Newitem = {
      item: item,
    }
    save[save.length] = Newitem
    that.setData({
      LineArr: that.data.LineArr,
      saveSt: save,
      saveStLenght: save.length,
    })
    wx.setStorageSync("save", save) // 设置制定缓存 
  },
  // 获取已收藏的路线
  getSave: function() {
    let that = this;
    let save = wx.getStorageSync("save"); // 获取制定缓存 
    that.setData({
      saveSt: save,
      saveStLenght: save.length,
    })
  },
  // 准到站提醒确认
  checkRemind: function(e) {
    let that = this,
      thisStName = e.currentTarget.dataset.thisstname;
    console.log(thisStName)
    that.setData({
      thisStName,
      remindShow: 1,
    })
  },
  // 激活准到站提醒
  remind: function(e) {
    this.setData({
      remindShow: 0,
    })
    let that = this;
    let formId = e.detail.formId,
      Checkitem = that.data.Checkitem,
      StationArr = that.data.StationArr,
      thisStName = that.data.thisStName,
      lastStname = "";
    wx.showToast({
      title: '准到"' + thisStName + '"将提醒"',
      icon: 'none',
      duration: 2000
    })
    for (let i in StationArr)
      if (StationArr[i].Name == thisStName)
        lastStname = StationArr[i - 1].Name;
    let dataArr = {
      what: "Remind",
      urlCheck: decodeURIComponent('http://www.zhbuswx.com/Handlers/BusQuery.ashx?handlerName=GetBusListOnRoad&lineName=' + Checkitem.Name + '&fromStation=' + Checkitem.FromStation + '&_='),
      url: "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=",
      form_id: formId,
      touser: app.globalData.openid,
      keyword1: Checkitem.Name,
      keyword2: Checkitem.FromStation,
      keyword3: Checkitem.ToStation,
      keyword4: '公交即将到达"' + thisStName + '"',
      lastStname: lastStname,
    }
    console.log('激活查询');
    app.reGetFn(app.globalData.url, dataArr).then(e => {
      console.log(e.data);
    })
  },
  // 
  showMap: function() {
    let this_ = this;
    this.setData({
      modalName: 'Modal'
    })
  }
})